import {getToken} from '@/utils/auth.js';
import store from "@/store/index.js";
import Vue from 'vue';


/**
 * @description: 校验是否登录
 * @param: String
 * @returns: Promise
 */

export function noTokenToLogin(flag = true) {
	return new Promise((resolve, reject) => {
		// 未登录过
		if (!getToken() && (Object.keys(store.state.userInfo).length == 0)) {
			uni.showModal({
				title: '提示',
				content: '您还未登录, 前往登录?',
				confirmColor: Vue.prototype.appPrimaryColor,
				success: function (res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/index'
						});
						if(flag) {
							reject();
						} else {
							resolve();
						}
						
					}
				}
			})
		} else {
			if(flag) {
				resolve();
			} else {
				reject();
			}
		}
	})
}

/**
 * @description: 跳转前判断
 * @param: String
 * @returns: Promise
 */

export function cuNavigateTo(url = '', isToken = true) { // 默认是navigateTo方式
	if(isToken) {
		noTokenToLogin().then(() => {
			uni.navigateTo({
				url
			})
		});
	} else {
		uni.navigateTo({
			url
		})
	}
};

export function formatTime(time, fmt) {
    if (!time) return '';
    else {
        const date = new Date(time);
        const o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'H+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds(),
            'q+': Math.floor((date.getMonth() + 3) / 3),
            S: date.getMilliseconds(),
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            );
        for (const k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length === 1
                        ? o[k]
                        : ('00' + o[k]).substr(('' + o[k]).length)
                );
            }
        }
        return fmt;
    }
}

/**
 * @param {Number} num 待处理数组
 * @param {Number} num1 待处理数组
 * @param {String} format 待处理数组
 */
export function dateGet(num, num1, format = 'MM/dd') {
    let weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    // 1 6
    let dateTime = [];
    let strDate = [];
    let curTime = new Date().getTime();
    // 前
    for (let i = 0; i < num; i++) {
        dateTime.push(curTime - 3600 * 24 * 1000 * (i + 1))
    }
    // 后
    for (let i = 0; i < num1 - num; i++) {
        dateTime.push(curTime + 3600 * 24 * 1000 * i)
    }
    dateTime.forEach(item => {
        strDate.push({
            date: formatTime(item, format),
            week: weekday[new Date(item).getDay()]
        });
    })
    return strDate
}

/**
 * @param {Number} num 待处理数组
 * @param {Number} num1 待处理数组
 * @param {String} format 待处理数组
 */
export function chunkArr(arr, size) {
	return Array.from({
    length: Math.ceil(arr.length / size)
}, (v, i) => arr.slice(i * size, i * size + size))
}
